<template>
  <div class="make-duomotai-base">
    <div class="upload-content">
      <el-upload
        ref="upload"
        class="avatar-uploader"
        :key="uploadKey"
        :action="`/tes/course/auto/make/resource-upload?courseId=${this.courseId}`"
        :show-file-list="false"
        :on-success="handleSuccess"
        :before-upload="beforeUpload"
        :on-error="handleError"
        :limit="1"
        accept=".pdf, .docx, .xlsx, .pptx, .txt, .jpg, .mp4"
        drag
      >
        <div class="upload-box">
          <div class="box-one">
            <div class="img-box">
              <img src="@/assets/img/zhishi/upload.png" />
            </div>
            <div class="one-txt">
              学生在进行章节知识点自学时，可查看与知识点匹配的学习资源，辅助自主学习，提升学习效果~
            </div>
            <div class="one-subtxt">
              导入本地文件，点击上传或拖拽文件到这里,支持上传文件（每个100MB）接受pdf、docx、xlsx、pptx、txt、jpg、mp4格式
            </div>
          </div>
        </div>
      </el-upload>
    </div>

    <!-- 表格区域 -->
    <div class="table-content">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column
          type="index"
          label="序号"
          width="120"
          :index="calculateIndex"
        />
        <el-table-column
          prop="fileName"
          label="文件名称"
          width="200"
          show-overflow-tooltip
        />
        <el-table-column label="涉及知识点" width="450" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.kbNames || "无" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="fileType" label="文件格式" width="150" />
        <el-table-column prop="fileSize" label="文件大小" width="150" />
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button
              link
              type="primary"
              size="small"
              @click.stop="setKnowledge(scope.row)"
              style="color: #457aff; font-size: 14px"
              >设置知识点</el-button
            >
            <el-button
              link
              type="primary"
              size="small"
              @click.stop="download(scope.row)"
              style="color: #457aff; font-size: 14px"
              >下载</el-button
            >
            <el-button
              link
              type="primary"
              size="small"
              @click.stop="handleDelete(scope.row)"
              style="color: #457aff; font-size: 14px"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        class="my_pagination"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        layout="prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 设置知道点弹窗 -->
    <el-dialog
      class="set-knowledge-dialog"
      v-model="showSetKnowledge"
      width="60%"
      :close-on-click-modal="false"
    >
      <el-form :model="form" label-width="auto">
        <!-- <el-form-item label="章节名称：">
          <el-select
            v-model="form.chapterName"
            placeholder="请选择"
            style="width: 500px"
          >
            <el-option
              v-for="item in chapterNameList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="涉及知识点：">
          <el-tree
            ref="tree"
            :data="treeData"
            show-checkbox
            node-key="value"
            default-expand-all
            :check-on-click-node="false"
            :expand-on-click-node="true"
            :props="defaultProps"
            class="tree-content"
          >
            <template #default="{ node }">
              <div class="custom-tree-node" @click.stop>
                <div class="tree-node-name">
                  <span>{{ node.label }}</span>
                </div>
              </div>
            </template>
          </el-tree>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button color="#155EEF" @click="saveFn()"> 保存 </el-button>
          <el-button @click="showSetKnowledge = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      courseId: "",
      fileId: "",
      uploadKey: 0, // 动态 key
      currentPage: 1,
      pageSize: 10,
      total: 0,
      showSetKnowledge: false,
      form: {
        chapterName: "",
      },
      defaultProps: {
        children: "children",
        label: "label",
      },
      chapterNameList: [],
      tableData: [],
      knowledgeList: [],
      treeData: [],
      loading: null, // loading实例
    };
  },
  created() {
    this.courseId = JSON.parse(localStorage.getItem("courseId"));
    this.getTableData();
  },
  methods: {
    // 计算表格序号
    calculateIndex(index) {
      return (this.currentPage - 1) * this.pageSize + index + 1;
    },

    // 获取文件列表
    getTableData() {
      this.$axios
        .get(
          `/tes/course/auto/make/resource?courseId=${this.courseId}&pageSize=${this.pageSize}&pageNum=${this.currentPage}`
        )
        .then((res) => {
          this.tableData = res.data.content;
          this.total = res.data.total;
          this.tableData.forEach((item) => {
            if (item.kbNames) {
              item.kbNames = item.kbNames.join(",");
            } else {
              item.kbNames = "无";
            }
          });
        });
    },

    handleSuccess(res, file) {
      console.log("上传成功：", res);
      this.$message.success("上传成功!");
      this.uploadKey += 1; // 修改 key 值，强制重新渲染组件
      this.getTableData();
      // 关闭loading
      if (this.loading) {
        this.loading.close();
        this.loading = null;
      }
    },
    beforeUpload(file) {
      // 支持上传文件（每个100MB）接受pdf、doc、docx、xlsx、ppt、txt、jpg、mp4格式
      const isPDF = file.type === "application/pdf";
      const isDoc = file.type === "application/msword";
      const isDocx =
        file.type ===
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
      const isXlsx =
        file.type ===
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      const isPpt = file.type === "application/vnd.ms-powerpoint";
      const isPptx =
        file.type ===
        "application/vnd.openxmlformats-officedocument.presentationml.presentation";
      const isTxt = file.type === "text/plain";
      const isJpg = file.type === "image/jpeg";
      const isPng = file.type === "image/png";
      const isMp4 = file.type === "video/mp4";
      // 检查文件大小是否大于100mb
      const isLt100M = file.size / 1024 / 1024 < 100;

      if (
        !isPDF &&
        // !isDoc &&
        !isDocx &&
        !isXlsx &&
        // !isPpt &&
        !isPptx &&
        !isTxt &&
        !isJpg &&
        // !isPng &&
        !isMp4
      ) {
        this.$message.error(
          "只能上传 pdf、docx、xlsx、pptx、txt、jpg、mp4 文件！"
        );
        return false;
      }
      if (!isLt100M) {
        this.$message.error("上传文件大小不能超过 100MB！");
        return false;
      }

      // 开始上传，显示loading
      this.loading = this.$loading({
        lock: true,
        text: "文件上传中...",
        background: "rgba(0, 0, 0, 0.7)",
      });

      return (
        isPDF ||
        isDocx ||
        isXlsx ||
        isPptx ||
        isTxt ||
        isJpg ||
        (isMp4 && isLt100M)
      ); // 返回校验结果
    },
    handleError() {
      this.$message.error("上传失败，请稍后再试!");
      this.uploadKey += 1; // 修改 key 值，强制重新渲染组件
      // 关闭loading
      if (this.loading) {
        this.loading.close();
        this.loading = null;
      }
    },

    // 设置知识点
    setKnowledge(row) {
      this.fileId = row.id;
      this.$axios
        .get(`/tes/course/auto/make/chapter-kb?courseId=${this.courseId}`)
        .then((res) => {
          this.showSetKnowledge = true;
          this.treeData = res.data;

          // 在树形数据加载完成后，先清空所有选中状态，然后设置已选择的知识点
          this.$nextTick(() => {
            // 先清空所有选中状态
            this.$refs.tree.setCheckedKeys([]);

            // 如果有已选择的知识点，则设置选中状态
            if (row.kbIds && Array.isArray(row.kbIds)) {
              this.$refs.tree.setCheckedKeys(row.kbIds);
            }
          });
        });
    },

    // 下载
    download(row) {
      window.open(row.filePath);
    },

    // 删除
    handleDelete(row) {
      this.$confirm("确定删除该文件吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$axios
          .delete(`/tes/course/auto/make/resource?id=${row.id}`)
          .then((res) => {
            this.$message.success("删除成功");
            this.getTableData();
            // 如果当前页没有数据了，回到上一页
            const maxPage = Math.ceil(this.total / this.pageSize);
            if (this.currentPage > maxPage && maxPage > 0) {
              this.currentPage = maxPage;
            }
          });
      });
    },

    // 分页
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.getTableData();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getTableData();
    },

    // 保存
    saveFn() {
      const selectNodes = this.$refs.tree.getCheckedKeys(true);
      this.$axios
        .post(
          `/tes/course/auto/make/resource-kb?id=${this.fileId}`,
          selectNodes
        )
        .then((res) => {
          this.$message.success("保存成功");
          this.getTableData();
          this.showSetKnowledge = false;
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.make-duomotai-base {
  background-color: #fff;
  padding: 40px 30px;
  box-sizing: border-box;
  min-height: 650px;
  .upload-content {
    .avatar-uploader {
      :deep(.el-upload-dragger) {
        border: none;
        padding: 0;
      }
      :deep(.el-upload) {
        width: 100%;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        border-radius: 10px;
        border: 1px dashed #bebebe;
        .upload-box {
          background: #fff;
          width: 100%;
          border-radius: 10px;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          padding: 40px 0 31px;
          > div {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
          }
          .box-one {
            width: 60%;
            .img-box {
              width: 31px;
              height: 23px;
              margin-bottom: 15px;
              img {
                width: 100%;
                height: 100%;
                object-fit: cover;
              }
            }
            .one-txt {
              font-size: 16px;
              color: #6b6a76;
              margin-bottom: 5px;
            }
            .one-subtxt {
              font-size: 14px;
              color: #a2a0b3;
            }
          }
        }
      }
      margin-bottom: 10px;
    }
  }

  .table-content {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    gap: 20px;
    margin-top: 20px;
    // padding: 0 30px;
    box-sizing: border-box;
    :deep(.el-popper.is-dark) {
      max-width: 30%;
      line-height: 22px;
    }
    :deep(.el-table__row) {
      .cell {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
    .my_pagination {
      :deep(.el-pager li.is-active) {
        color: #457aff;
      }
      :deep(.el-pager li:hover) {
        color: #457aff;
      }
    }
  }
}
</style>
<!-- 弹窗样式 -->
<style lang="scss">
.set-knowledge-dialog {
  .el-dialog {
    height: 680px !important;
  }

  .el-dialog__body {
    padding: 25px !important;
  }

  .el-textarea__inner {
    height: 323px !important;
    min-height: 323px !important;
  }

  .tree-content {
    width: 100%;
    height: 400px;
    overflow-y: auto;
    border: 1px solid #e5e5e5;
    padding: 10px;
    box-sizing: border-box;
    &::-webkit-scrollbar {
      width: 4px;
    }
    &::-webkit-scrollbar-thumb {
      background-color: #e5e5e5;
    }
    &::-webkit-scrollbar-track {
      background-color: #f5f5f5;
    }
  }
}
</style>